//
//  MachineTranslationManager.m
//  GLUZ
//
//  Created by GS on 2025/2/23.
//

#import "MTManager.h"
#import "CryptoHelper.h"
@implementation MTManager

// Authorization
+ (NSString *)generateAuthorizationWithApiKey:(NSString *)apiKey apiSecret:(NSString *)apiSecret host:(NSString *)host date:(NSString *)date requestLine:(NSString *)requestLine{
    NSString *signature_origin = [NSString stringWithFormat:@"host: %@\ndate: %@\n%@",host,date,requestLine];
    
    NSString *signature = [CryptoHelper hmacSHA256:signature_origin withKey:apiSecret];
    
    
    NSString * authorization_origin = [NSString stringWithFormat: @"api_key=\"%@\",algorithm=\"hmac-sha256\",headers=\"host date request-line\",signature=\"%@\"",apiKey,signature];
    NSString * authorization = [CryptoHelper base64Encode:authorization_origin];
    
    return authorization;
    
}

/// 发送 POST 请求
+ (void)translationFrom:(NSString *)from to:(NSString *)to text:(NSString *)text success:(TranslationSuccessBlock)success failure:(TranslationFailureBlock)failure{
    
    if ([text isKindOfClass:[NSString class]]) {
        NSLog(@"text 是 字符串 : %@", [text description]);
    } else {
        NSLog(@"text 不是 字符串 : %@", [text description]);
    }
    
    NSString *apiKey = @"e51f6c5911b7737aa742c70fefd3e2c7";  // 替换为你的 API Key
    NSString *apiSecret = @"NmI3YjI1M2I5YjQ4YTMxZjE4YmQ5NGUy";  // 替换为你的 API Secret
    
//    NSString *apiKey = @"651bbdc1f80148aee52a2fa35a3f8639";  // 替换为你的 API Key
//    NSString *apiSecret = @"NWJkOTFkM2I3MTI2ZDU0MjQ1ZTM1ZDVi";  // 替换为你的 API Secret
    
    NSString *host = @"itrans.xf-yun.com";
    NSString *date = [CryptoHelper getRFC1123Date];
    NSString *requestLine = @"POST /v1/its HTTP/1.1";
    
    // 生成 Authorization 头部
    NSString *authorization = [self generateAuthorizationWithApiKey:apiKey apiSecret:apiSecret host:host date:date requestLine:requestLine];
    authorization = [authorization stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    date = [date stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    host = [host stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSString *urlString =[NSString stringWithFormat:@"https://itrans.xf-yun.com/v1/its?authorization=%@&host=%@&date=%@",authorization,host,date];
    
    
    // JSON 请求体
    NSDictionary *requestBody = @{
        @"header": @{
            @"app_id": @"d03ed103",
            @"status": @3,
        },
        @"parameter": @{
            @"its": @{
                @"from": from,
                @"to": to,
                @"result": @{}
            }
        },
        @"payload": @{
            @"input_data": @{
                @"encoding": @"utf8",
                @"status": @3,
                @"text": [CryptoHelper base64Encode:text]
            }
        }
    };
    
    // 将请求体转换为 JSON
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestBody options:0 error:&error];
    if (error) {
        NSLog(@"JSON 生成失败: %@", error.localizedDescription);
        return;
    }
    
    // 创建 URLRequest
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = jsonData;
    
    // 设置 HTTP 头部
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // 创建 NSURLSession 并发送请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"请求失败: %@", error.localizedDescription);
            if (failure) {
                failure(error);
            }
            return;
        }
        
        if (data) {
            NSError *jsonError;
            NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
            
            if (!jsonError && responseDict) {
                NSLog(@"[MTManager] text : %@", text);
                NSLog(@"[MTManager] 请求参数 : %@", requestBody);
                NSLog(@"[MTManager] 翻译结果 : %@", responseDict);
                NSString *base64Text = responseDict[@"payload"][@"result"][@"text"];
                
                if (base64Text) {
                    NSString *decodedText = [CryptoHelper base64Decode:base64Text];
                    
                    NSData *jsonData = [decodedText dataUsingEncoding:NSUTF8StringEncoding];
                    NSDictionary *jsonDict = nil;
                    
                    @try {
                        jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
                    } @catch (NSException *exception) {
                        NSLog(@"解析 JSON 数据时发生异常: %@", exception.reason);
                        if (failure) {
                            failure([NSError errorWithDomain:@"ParsingError" code:-1 userInfo:@{NSLocalizedDescriptionKey: exception.reason}]);
                        }
                        return;
                    }
                    
                    if (jsonDict) {
                        NSDictionary *trans_result = [jsonDict valueForKeyPath:@"trans_result"];
                        
                        if (trans_result) {
                            NSString *dst = trans_result[@"dst"];
                            NSString *src = trans_result[@"src"];

                            NSLog(@"翻译结果: %@ dst = %@ ,src = %@", trans_result, trans_result[@"dst"], trans_result[@"src"]);
                            if (success) {
                                success(src,dst);
                            }
                        } else {
                            NSLog(@"未找到 'trans_result' 键");
                            if (failure) {
                                failure([NSError errorWithDomain:@"MissingResultError" code:-2 userInfo:@{NSLocalizedDescriptionKey: @"未找到 'trans_result' 键"}]);
                            }
                        }
                    } else {
                        NSLog(@"无法解析 JSON 数据");
                        if (failure) {
                            failure([NSError errorWithDomain:@"ParsingError" code:-3 userInfo:@{NSLocalizedDescriptionKey: @"无法解析 JSON 数据"}]);
                        }
                    }
                } else {
                    NSLog(@"未找到 base64 编码文本");
                    if (failure) {
                        failure([NSError errorWithDomain:@"MissingBase64TextError" code:-4 userInfo:@{NSLocalizedDescriptionKey: @"未找到 base64 编码文本"}]);
                    }
                }
            } else {
                NSLog(@"JSON 解析失败: %@", jsonError.localizedDescription);
                if (failure) {
                    failure(jsonError);
                }
            }
        }
    }];
    
    [task resume];
}

@end
